import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse, RequestConfig,  } from '@/types/axios-types'
import { AxiosConst } from '@/constants/framework/axios-const'
import { defaultRequestInterceptors, defaultResponseInterceptors } from './config'

// 创建axios实例
const axiosInstance: AxiosInstance = axios.create({
  timeout: AxiosConst.API_TIMEOUT as number,
  baseURL: AxiosConst.API_BASE_URL as string,
});

// 使用请求拦截器绑定AbortController,用于取消请求
const abortControllerMap: Map<string, AbortController> = new Map();
axiosInstance.interceptors.request.use((res: InternalAxiosRequestConfig) => {
  const controller = new AbortController();
  const url = res.url || '';
  res.signal = controller.signal;
  abortControllerMap.set(url, controller);
  return res;
});

// 在响应拦截器中删除abortControllerMap里请求过的key
axiosInstance.interceptors.response.use((res: AxiosResponse) => {
  const url = res.config.url || '';
  abortControllerMap.delete(url);
  // 这里不能做任何处理，否则后面的 interceptors 拿不到完整的上下文了
  return res;
});

axiosInstance.interceptors.request.use(defaultRequestInterceptors);
axiosInstance.interceptors.response.use(defaultResponseInterceptors);

const service = {
  request: (config: RequestConfig) => {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptors) {
        config = config.interceptors.requestInterceptors(config as any);
      }

      axiosInstance
        .request(config)
        .then((res) => {
          resolve(res);
        })
        .catch((err: any) => {
          reject(err);
        });
    });
  },
  cancelRequest: (url: string | string[]) => {
    const urlList = Array.isArray(url) ? url : [url];
    for (const _url of urlList) {
      abortControllerMap.get(_url)?.abort();
      abortControllerMap.delete(_url);
    }
  },
  cancelAllRequest() {
    for (const [_, controller] of abortControllerMap) {
      controller.abort();
    }
    abortControllerMap.clear();
  },
};

export default service;
